package com.pxmeta.party.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.pxmeta.common.core.redis.RedisCache;
import com.pxmeta.common.exception.ServiceException;
import com.pxmeta.common.utils.ThreadPoolExecutorUtil;
import com.pxmeta.party.entity.*;
import com.pxmeta.party.entity.vo.*;
import com.pxmeta.party.mapper.ActivityAdAstraRecordMapper;
import com.pxmeta.party.service.*;
import com.pxmeta.user.entity.User;
import com.pxmeta.user.service.IUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class ActivityAdAstraRecordServiceImpl extends ServiceImpl<ActivityAdAstraRecordMapper, ActivityAdAstraRecord> implements IActivityAdAstraRecordService {
    @Autowired
    private IActivityAdAstraService activityAdAstraService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IGiftService giftService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IUserGiftService userGiftService;

    @Autowired
    private ILotteryLuckyUserService lotteryLuckyUserService;

    @Autowired
    private IActivityAdAstraUserRecordService activityAdAstraUserRecordService;

    @Autowired
    private ITurntableNumberService turntableNumberService;


    private static final int WEIGHT_MULTIPLIER = 10000; // Adjust this multiplier as needed


    @Override
    public ActivityAdAstraRecord getCurrentRecord() {
        LambdaQueryWrapper<ActivityAdAstraRecord> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ActivityAdAstraRecord::getStatus, 0);
        return this.getOne(wrapper);
    }


    @Override
    public ActivityAdAstraDispatchResultVO getDispatchStatus(Long userId) {
        ActivityAdAstraRecord currentRecord = this.getCurrentRecord();
        //获取结束时间
        Long endTimeMillis = redisCache.getCacheObject("countdown_time");
        double time = (double) (endTimeMillis - System.currentTimeMillis()) / 1000;
        //如果结束时间小于10秒，则无法继续下注
        if (time > 10) {
            currentRecord = this.getLastRecord();
        }

        LambdaQueryWrapper<ActivityAdAstraUserRecord> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ActivityAdAstraUserRecord::getUserId, userId)
                .eq(ActivityAdAstraUserRecord::getRecordId, currentRecord.getId());

        List<ActivityAdAstraUserRecord> list = activityAdAstraUserRecordService.list(wrapper);
        ActivityAdAstraRecord finalCurrentRecord = currentRecord;
        int sum = list.stream().filter(l -> l.getStarId().equals(finalCurrentRecord.getSuccessId())).mapToInt(ActivityAdAstraUserRecord::getCount).sum();


        wrapper.clear();
        wrapper.eq(ActivityAdAstraUserRecord::getRecordId, currentRecord.getId())
                .eq(ActivityAdAstraUserRecord::getStarId, currentRecord.getSuccessId());

        Set<Long> successUserIds = activityAdAstraUserRecordService.list(wrapper).stream().map(ActivityAdAstraUserRecord::getUserId).collect(Collectors.toSet());

        ActivityAdAstraDispatchResultVO vo = new ActivityAdAstraDispatchResultVO();
        int status;
        if (list.isEmpty()) {
            //未派遣
            status = 0;
        } else {
            List<Long> starIds = list.stream().map(ActivityAdAstraUserRecord::getStarId).collect(Collectors.toList());
            if (starIds.contains(currentRecord.getSuccessId())) {
                status = 1;
                vo.setCount(sum);

                List<LotteryLuckyUser> lotteryLuckyUsers = lotteryLuckyUserService.getByRecordId(userId, currentRecord.getId());
                int coins = lotteryLuckyUsers.stream().mapToInt(LotteryLuckyUser::getPrice).sum();
                List<Gift> giftList = giftService.spendCoins(coins, 11, 625000, 500000, 100000, 10000, 2500);
                List<ActivityAdAstraDispatchGiftVO> gifts = Lists.newArrayList();

                for (Gift gift : giftList) {
                    Boolean isContains = Boolean.FALSE;
                    for (ActivityAdAstraDispatchGiftVO giftVO : gifts) {
                        if (gift.getId().equals(giftVO.getId())) {
                            giftVO.setCount(giftVO.getCount() + 1);
                            isContains = Boolean.TRUE;
                            break;
                        }
                    }

                    if (isContains) {
                        continue;
                    }

                    ActivityAdAstraDispatchGiftVO giftVO = new ActivityAdAstraDispatchGiftVO();
                    giftVO.setCount(1);
                    giftVO.setName(gift.getName());
                    giftVO.setIcon(gift.getIcon());
                    giftVO.setId(gift.getId());
                    gifts.add(giftVO);
                }

                vo.setGiftList(gifts);
            } else {
                status = -1;
            }
        }

        ActivityAdAstra adAstra = activityAdAstraService.getById(currentRecord.getSuccessId());
        vo.setStatus(status);
        vo.setUserCount(successUserIds.size());
        vo.setSuccessStar(adAstra);

        return vo;
    }


    private ActivityAdAstraRecord getLastRecord() {

        LambdaQueryWrapper<ActivityAdAstraRecord> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ActivityAdAstraRecord::getStatus, 1)
                .orderByDesc(ActivityAdAstraRecord::getCreateTime)
                .last("limit 1");
        return this.getOne(wrapper);
    }


    @Override
    public void computeRecord() {
        log.info("开始执行computeRecord....");
        ActivityAdAstraRecord record = this.getCurrentRecord();
        List<Long> allStarIds = activityAdAstraService.list().stream().map(ActivityAdAstra::getId).collect(Collectors.toList());
        TurntableNumber turntableNumber = turntableNumberService.getTurntableNumber(7);
        List<ActivityAdAstraUserRecord> userRecords = activityAdAstraUserRecordService.getByRecordId(record.getId());
        //获取中奖用户
        List<ActivityAdAstraUserRecord> successRecords = userRecords.stream().filter(l -> l.getStatus() == 1).collect(Collectors.toList());
        //中奖总金额
        int totalPrice = successRecords.stream().mapToInt(ActivityAdAstraUserRecord::getRewardPrice).sum();
        Set<Long> setIds = userRecords.stream().map(ActivityAdAstraUserRecord::getStarId).collect(Collectors.toSet());
        //判断奖池是否亏损
        BigDecimal consumeNumber = turntableNumber.getConsumeNumber();
        BigDecimal giftNumber = turntableNumber.getGiftNumber();
        Double rebateRatio = turntableNumber.getRebateRatio();
        double totalGiftNumber = giftNumber.add(BigDecimal.valueOf(totalPrice)).doubleValue();
        log.info("开始执行computeRecord，判断是否亏损，totalNumber:{},consumeNumber:{}", totalGiftNumber, consumeNumber.doubleValue());
        if ((totalGiftNumber > consumeNumber.doubleValue())
                || (totalPrice > rebateRatio * (consumeNumber.doubleValue() - totalGiftNumber))
                || (consumeNumber.doubleValue() - totalGiftNumber < 0)) {
            totalPrice = 0;
            Long finalSuccessId = null;
            //平台亏损 重置奖品
            //优先判断用户没有下注的星球。
            for (Long starId : allStarIds) {
                if (!setIds.contains(starId)) {
                    finalSuccessId = starId;
                    break;
                }
            }

            if (finalSuccessId == null) {
                //如果所有球都下注的，则查询金额最小的。
                ActivityAdAstraStarPriceVO vo = baseMapper.selectMinStarByRecordId(record.getId());
                finalSuccessId = vo.getStarId();
            }

            log.info("开始执行computeRecord，判断是否亏损，平台亏损，重置奖励，新奖励id:{}", finalSuccessId);
            record.setSuccessId(finalSuccessId);
            this.updateById(record);

            ActivityAdAstra success = activityAdAstraService.getById(finalSuccessId);

            //重置成功记录
            if (!successRecords.isEmpty()) {
                log.info("开始执行computeRecord，判断是否亏损，重置成功记录，数量：{}", successRecords.size());
                successRecords.forEach(s -> s.setStatus(0));
                activityAdAstraUserRecordService.updateBatchById(successRecords);
            }
            Long finalSuccessId1 = finalSuccessId;
            List<ActivityAdAstraUserRecord> finalSuccessRecordList = userRecords.stream().filter(u -> u.getStarId().equals(finalSuccessId1)).collect(Collectors.toList());
            if (!finalSuccessRecordList.isEmpty()) {
                finalSuccessRecordList.forEach(fs -> {
                    fs.setStatus(1);
                    fs.setRewardPrice(success.getMagnification() * fs.getCount() * 500);
                });
                activityAdAstraUserRecordService.updateBatchById(finalSuccessRecordList);

                log.info("开始执行computeRecord，奖品已被重置，开始保存幸运用户记录，finalSuccessRecordList：{}", finalSuccessRecordList);

                this.saveLotteryLuckyUsers(finalSuccessRecordList);
                totalPrice = finalSuccessRecordList.stream().mapToInt(ActivityAdAstraUserRecord::getRewardPrice).sum();
            }
        } else {

            log.info("开始执行computeRecord，奖品未被重置，开始保存幸运用户记录，finalSuccessRecordList：{}", successRecords);
            this.saveLotteryLuckyUsers(successRecords);
        }

        giftNumber = giftNumber.add(BigDecimal.valueOf(totalPrice));
        turntableNumber.setGiftNumber(giftNumber);
        turntableNumberService.updateById(turntableNumber);
    }

    @Override
    public List<ActivityAdAstraRecord> getHourRecordList() {
        return baseMapper.getHourRecordList();
    }

    @Override
    public List<ActivityAdAstraRecord> getTodayRecordList() {
        return baseMapper.getTodayRecordList();
    }

    @Override
    public List<ActivityAdAstraRecord> getLastDayRecordList() {
        return baseMapper.getLastDayRecordList();
    }

    @Override
    public ActivityAdAstraDataLateVO getLateCountList() {


        List<ActivityAdAstraDataLateItemVO> lateRecordList = baseMapper.getLateRecordList();
        List<ActivityAdAstraDataLateItemVO> tuLateList = Lists.newLinkedList();

        List<ActivityAdAstraDataLateItemVO> kaiLateList = Lists.newLinkedList();

        List<ActivityAdAstraDataLateItemVO> tianLateList = Lists.newLinkedList();

        List<ActivityAdAstraDataLateItemVO> haiLateList = Lists.newLinkedList();


        for (ActivityAdAstraDataLateItemVO vo : lateRecordList) {
            if (vo.getId().equals(1L)) {
                vo.setLateName("土晚点");
                tuLateList.add(vo);
            }
            if (vo.getId().equals(8L)) {
                vo.setLateName("开晚点");
                kaiLateList.add(vo);
            }

            if (vo.getId().equals(7L)) {
                vo.setLateName("天晚点");
                tianLateList.add(vo);
            }
            if (vo.getId().equals(5L)) {
                vo.setLateName("海晚点");
                haiLateList.add(vo);
            }
        }

        this.setLastVo(kaiLateList);
        this.setLastVo(tuLateList);
        this.setLastVo(haiLateList);
        this.setLastVo(tianLateList);

        ActivityAdAstraDataLateVO vo = new ActivityAdAstraDataLateVO();

        int kaiStartIndex = Math.max(0, kaiLateList.size() - 30);
        int tuStartIndex = Math.max(0, tuLateList.size() - 30);
        int haiStartIndex = Math.max(0, haiLateList.size() - 30);
        int tianStartIndex = Math.max(0, tianLateList.size() - 30);

        vo.setKaiLateList(kaiLateList.subList(kaiStartIndex, kaiLateList.size()));

        vo.setTuLateList(tuLateList.subList(tuStartIndex, tuLateList.size()));

        vo.setHaiLateList(haiLateList.subList(haiStartIndex, haiLateList.size()));
        vo.setTianLateList(tianLateList.subList(tianStartIndex, tianLateList.size()));

        return vo;
    }


    private void setLastVo(List<ActivityAdAstraDataLateItemVO> list) {
        ActivityAdAstraDataLateItemVO lastVo = list.get(list.size() - 1);
        LocalDateTime lastDateTime = lastVo.getDateTime();

        LocalDateTime dateTime = LocalDateTime.now();
        int monthValue = dateTime.getMonthValue();
        int day = dateTime.getDayOfMonth();
        int hour = dateTime.getHour();
        int minute = dateTime.getMinute();

        Duration duration = Duration.between(lastDateTime, dateTime);

        ActivityAdAstraDataLateItemVO finalLastVo = new ActivityAdAstraDataLateItemVO();
        finalLastVo.setTime(monthValue + "/" + day + " " + hour + ":" + minute);

        finalLastVo.setLateName(lastVo.getLateName());
        finalLastVo.setCount((int) duration.toMinutes());

        list.add(finalLastVo);
    }

    private void saveLotteryLuckyUsers(List<ActivityAdAstraUserRecord> finalSuccessRecordList) {
        if (finalSuccessRecordList.isEmpty()) {
            return;
        }
        List<Long> userIds = finalSuccessRecordList.stream().map(ActivityAdAstraUserRecord::getUserId).collect(Collectors.toList());
        List<User> users = userService.listByIds(userIds);
        List<LotteryLuckyUser> lotteryLuckyUsers = Lists.newLinkedList();
        for (ActivityAdAstraUserRecord userRecord : finalSuccessRecordList) {
            Long userId = userRecord.getUserId();
            User user = users.stream().filter(u -> u.getId().equals(userId)).findFirst().get();
            LotteryLuckyUser lotteryLuckyUser = new LotteryLuckyUser();
            lotteryLuckyUser.setUserId(userId);
            lotteryLuckyUser.setConsumePrice((double) userRecord.getTotalPrice());
            String nickname = user.getNickname();
            lotteryLuckyUser.setRecordId(userRecord.getRecordId());
            lotteryLuckyUser.setGiftId(null);
            lotteryLuckyUser.setCount(0);
            lotteryLuckyUser.setNickname(user.getNickname());
            lotteryLuckyUser.setAvatar(user.getAvatar());
            lotteryLuckyUser.setType(7);
            lotteryLuckyUser.setPrice(userRecord.getRewardPrice());


            if (userRecord.getRewardPrice() > 100000) {
                Runnable task = () -> {
                    String msg = String.format("%s在星际探险中获得价值%s万金币的礼物", user.getNickname(), userRecord.getRewardPrice()/10000);
                    giftService.sendFullServerNotification(msg);
                };
                ThreadPoolExecutorUtil.submit(task);
            }
            lotteryLuckyUser.setContent("恭喜 " + nickname + " " + "获得" + userRecord.getCount() + "探险值");
            lotteryLuckyUsers.add(lotteryLuckyUser);
        }
        if (!lotteryLuckyUsers.isEmpty()) {
            lotteryLuckyUserService.saveBatch(lotteryLuckyUsers);
        }
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void resetRecord() {
        ActivityAdAstraRecord record = this.getCurrentRecord();
        if (record != null) {
            record.setStatus(1);
            this.updateById(record);
            List<ActivityAdAstraUserRecord> records = activityAdAstraUserRecordService.getByRecordId(record.getId());

            List<ActivityAdAstraUserRecord> collect = records.stream().filter(r -> r.getStatus() == 1).collect(Collectors.toList());
//            List<LotteryLuckyUser> luckyUsers = lotteryLuckyUserService.getByRecordId(record.getId());
//            Map<Long, Integer> map = new HashMap<>();
//            for (ActivityAdAstraUserRecord luckyUser : collect) {
//                Integer value = map.get(luckyUser.getUserId());
//                if (value != null) {
//                    value += luckyUser.getRewardPrice();
//                } else {
//                    value = luckyUser.getRewardPrice();
//                }
//                map.put(luckyUser.getUserId(), value);
//            }

            for (ActivityAdAstraUserRecord userRecord : collect) {
                List<Gift> gifts = giftService.spendCoins(userRecord.getRewardPrice(), 11, 625000, 500000, 100000, 10000, 2500);
                userGiftService.addUserGift(userRecord.getUserId(), gifts);
            }
        }

        ActivityAdAstraRecord astraRecord = new ActivityAdAstraRecord();

        long count = this.count();
        LocalDateTime now = LocalDateTime.now();
        int year = now.getYear();
        int monthValue = now.getMonthValue();
        int dayOfMonth = now.getDayOfMonth();

        String id = year + "" + monthValue + "" + dayOfMonth + "" + count;

        astraRecord.setId(Long.parseLong(id));
        astraRecord.setStatus(0);
        //开奖
        List<ActivityAdAstra> list = activityAdAstraService.list();
        HashMap<ActivityAdAstra, Double> map = Maps.newHashMap();
        for (ActivityAdAstra activityAdAstra : list) {
            map.put(activityAdAstra, activityAdAstra.getProbability());
        }

        ActivityAdAstra success = weightRandom(map);
        astraRecord.setSuccessId(success.getId());
        this.save(astraRecord);
    }

    private ActivityAdAstra weightRandom(Map<ActivityAdAstra, Double> map) {
        //获取map里的key值集合
        List<ActivityAdAstra> weights = new ArrayList<>();
        for (Map.Entry<ActivityAdAstra, Double> entry : map.entrySet()) {
            ActivityAdAstra weightStr = entry.getKey();
            double fractionalWeight = entry.getValue();
            int integerWeight = (int) (fractionalWeight * WEIGHT_MULTIPLIER);

            for (int i = 0; i < integerWeight; i++) {
                weights.add(weightStr);
            }
        }

        // Randomly select an item from the weighted list
        int idx = new Random().nextInt(weights.size());
        return weights.get(idx);
    }

    @Override
    public List<ActivityAdAstraRecordVO> getDispatchRecord(Long userId, Integer type) {
        LambdaQueryWrapper<ActivityAdAstraRecord> wrapper = Wrappers.lambdaQuery();

        wrapper.eq(ActivityAdAstraRecord::getStatus, 1)
                .orderByDesc(ActivityAdAstraRecord::getCreateTime)
                .last("limit 100");
        List<ActivityAdAstraRecord> list = this.list(wrapper);
        List<Long> recordIds = list.stream().map(ActivityAdAstraRecord::getId).collect(Collectors.toList());

        //获取用户所有派遣记录
        List<ActivityAdAstraUserRecord> userAllRecords = activityAdAstraUserRecordService.getByRecordIds(recordIds, userId);

        //获取所有奖品
        List<Long> successIds = list.stream().map(ActivityAdAstraRecord::getSuccessId).collect(Collectors.toList());
        List<ActivityAdAstra> successStarList = activityAdAstraService.listByIds(successIds);
        List<Long> allStarIds = userAllRecords.stream().map(ActivityAdAstraUserRecord::getStarId).collect(Collectors.toList());

        List<ActivityAdAstra> allStarList = Lists.newLinkedList();
        if (!allStarIds.isEmpty()) {
            allStarList = activityAdAstraService.listByIds(allStarIds);
        }

        List<ActivityAdAstraRecordVO> finalList = Lists.newLinkedList();
        for (ActivityAdAstraRecord record : list) {


            Long successId = record.getSuccessId();//成功的星球。
            //获取用户派遣的星球
            Long recordId = record.getId();
            List<ActivityAdAstraUserRecord> userRecords = userAllRecords.stream().filter(r -> r.getRecordId().equals(recordId)).collect(Collectors.toList());

            List<Long> starIds = userRecords.stream().map(ActivityAdAstraUserRecord::getStarId).collect(Collectors.toList());
            Optional<ActivityAdAstra> first = successStarList.stream().filter(s -> s.getId().equals(successId)).findFirst();
            if (first.isPresent()) {
                ActivityAdAstraRecordVO vo = new ActivityAdAstraRecordVO();
                ActivityAdAstra successStar = first.get();
                vo.setSuccessStar(successStar.getName());
                if (!starIds.isEmpty()) {
                    List<ActivityAdAstra> starList = allStarList.stream().filter(a -> starIds.contains(a.getId())).collect(Collectors.toList());
                    Set<ActivityAdAstraDispatchStarVO> dispatchStars = starList.stream().map(s -> {
                        ActivityAdAstraDispatchStarVO starVO = new ActivityAdAstraDispatchStarVO();
                        starVO.setName(s.getName());
                        int sum = userRecords.stream().filter(u -> u.getStarId().equals(s.getId())).mapToInt(ActivityAdAstraUserRecord::getCount).sum();
                        starVO.setCount(sum);
                        return starVO;

                    }).collect(Collectors.toSet());
                    vo.setDispatchStar(dispatchStars);

                    if (dispatchStars.stream().map(ActivityAdAstraDispatchStarVO::getName).collect(Collectors.toList()).contains(successStar.getName())) {
                        vo.setStatus(1);

                        List<LotteryLuckyUser> lotteryLuckyUsers = lotteryLuckyUserService.getByRecordId(userId, recordId);
                        int coins = lotteryLuckyUsers.stream().mapToInt(LotteryLuckyUser::getPrice).sum();
                        List<Gift> giftList = giftService.spendCoins(coins, 11, 625000, 500000, 100000, 10000, 2500);
                        List<ActivityAdAstraDispatchGiftVO> gifts = Lists.newArrayList();

                        for (Gift gift : giftList) {

                            Boolean isContains = Boolean.FALSE;
                            for (ActivityAdAstraDispatchGiftVO giftVO : gifts) {
                                if (gift.getId().equals(giftVO.getId())) {
                                    giftVO.setCount(giftVO.getCount() + 1);
                                    isContains = Boolean.TRUE;
                                    break;
                                }
                            }

                            if (isContains) {
                                continue;
                            }

                            ActivityAdAstraDispatchGiftVO giftVO = new ActivityAdAstraDispatchGiftVO();
                            giftVO.setCount(1);
                            giftVO.setName(gift.getName());
                            giftVO.setIcon(gift.getIcon());
                            giftVO.setId(gift.getId());
                            gifts.add(giftVO);
                        }

                        vo.setGiftList(gifts);
                    } else {
                        vo.setStatus(-1);
                    }

                } else {
                    if (type == 1) {
                        continue;
                    }
                    vo.setStatus(0);
                }
                vo.setCreateTime(record.getCreateTime());
                finalList.add(vo);
            }
        }

        return finalList;
    }

    @Override
    public List<ActivityAdAstraUserRankingVO> getUserRanking(Integer page, Integer size) {
        List<User> users = baseMapper.getRankingUsers(new Page<>(page, size));

        List<ActivityAdAstraUserRankingVO> vos = Lists.newLinkedList();
        for (int i = 0; i < users.size(); i++) {
            User user = users.get(i);
            List<ActivityAdAstraStarVO> starList = baseMapper.getUserStarList(user.getId());
            ActivityAdAstraUserRankingVO vo = new ActivityAdAstraUserRankingVO();
            vo.setAvatar(user.getAvatar());
            vo.setNickname(user.getNickname());
            vo.setStarList(starList);
            List<LotteryLuckyUser> lotteryLuckyUsers = lotteryLuckyUserService.getByRecordId(user.getId(), null);
//            int coins = lotteryLuckyUsers.stream().mapToInt(LotteryLuckyUser::getPrice).sum();

            List<Gift> giftList = Lists.newLinkedList();
            for (LotteryLuckyUser lotteryLuckyUser : lotteryLuckyUsers) {
                giftList.addAll(giftService.spendCoins(lotteryLuckyUser.getPrice(), 11, 625000, 500000, 100000, 10000, 2500));
            }
            List<ActivityAdAstraDispatchGiftVO> gifts = Lists.newArrayList();

            for (Gift gift : giftList) {

                Boolean isContains = Boolean.FALSE;
                for (ActivityAdAstraDispatchGiftVO giftVO : gifts) {
                    if (gift.getId().equals(giftVO.getId())) {
                        giftVO.setCount(giftVO.getCount() + 1);
                        isContains = Boolean.TRUE;
                        break;
                    }
                }

                if (isContains) {
                    continue;
                }

                ActivityAdAstraDispatchGiftVO giftVO = new ActivityAdAstraDispatchGiftVO();
                giftVO.setCount(1);
                giftVO.setName(gift.getName());
                giftVO.setIcon(gift.getIcon());
                giftVO.setPrice(gift.getPrice());
                giftVO.setId(gift.getId());
                gifts.add(giftVO);
            }

            // 使用自定义比较器进行倒序排序
            gifts.sort((p1, p2) -> {
                return Integer.compare(p2.getPrice(), p1.getPrice()); // 倒序排序
            });
            gifts = gifts.stream().limit(3).collect(Collectors.toList());
            vo.setGiftList(gifts);
            vos.add(i, vo);
        }
        return vos;
    }
}
